<template>
  <div class="register-container">
    <el-card class="register-card">
      <h2 class="register-title">用户注册</h2>
      <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" status-icon label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" type="email" placeholder="请输入邮箱" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" autocomplete="off"
            show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请确认密码" autocomplete="off"
            show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="default" @click="resetForm">重置</el-button>
          <el-button type="primary" @click="handleRegister" :loading="loading">{{ loading ? '注册中...' : '注册'
          }}</el-button>
          <el-button type="primary" @click="handleReturn">返回登录</el-button>
        </el-form-item>
        <div v-if="errorMsg" class="error-message">{{ errorMsg }}</div>
        <div v-if="successMsg" class="success-message">{{ successMsg }}</div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '../stores/auth';
// 导入验证规则
import { usernameRules, passwordRules, emailRules } from '../utils/validationRules';
const router = useRouter();
const authStore = useAuthStore();
const registerFormRef = ref(null);
const loading = ref(false);
const errorMsg = ref('');
const successMsg = ref('');

const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
});
//验证规则
const registerRules = {
  username: usernameRules,
  password: passwordRules,
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.value.password) {
          callback(new Error('两次密码输入不一致'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ],
  email: emailRules,
};
const resetForm = () => {
  registerFormRef.value.resetFields();
  errorMsg.value = '';
  successMsg.value = '';
};
//用户注册√
const handleRegister = async () => {
  try {
    await registerFormRef.value.validate();
    loading.value = true;
    errorMsg.value = '';
    successMsg.value = '';

    // 注册API调用
 const response = await new Promise((resolve, reject) => {
      authStore.register(registerForm.value.username, registerForm.value.password, registerForm.value.email)
        .then(() => {
          setTimeout(() => {
            resolve({ success: true }); // 延迟1秒后返回成功结果
          }, 500);
        }).catch((error) => {
          reject(error); // 如果注册失败，调用 reject
        });
    });
    if (response.success) {
      successMsg.value = '注册成功，请登录';
      // 注册成功后跳转到登录页面
      setTimeout(() => {
        router.push('/login');
      }, 1500);
    }
  } catch (error) {
    if (error instanceof Error) {
      errorMsg.value = error.message;
    } else {
      errorMsg.value = '注册失败，请重试';
    }
  } finally {
    loading.value = false;
  }
};
const handleReturn = async () => {
  router.push('/login');
}
</script>
<style scoped>
@import url('../styles/registercss.css');
</style>
